package com.hbisedm.interninfosys.intern.controller;


import cn.afterturn.easypoi.entity.vo.TemplateWordConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.word.WordExportUtil;
import cn.afterturn.easypoi.word.entity.WordImageEntity;
import cn.hutool.extra.cglib.CglibUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hbisedm.interninfosys.commonutils.LocalVariables;
import com.hbisedm.interninfosys.commonutils.R;
import com.hbisedm.interninfosys.intern.entity.*;
import com.hbisedm.interninfosys.intern.entity.vo.RelevanceUserVo;
import com.hbisedm.interninfosys.intern.entity.vo.UnitLetterVo;
import com.hbisedm.interninfosys.intern.entity.wordVo.UnitLetter;
import com.hbisedm.interninfosys.intern.service.*;
import com.hbisedm.interninfosys.utils.AliyunOssUtil;
import com.hbisedm.interninfosys.utils.TransUtils;
import lombok.SneakyThrows;
import org.apache.commons.collections4.Get;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Sam
 * @since 2020-12-03
 */
@RestController
@RequestMapping("/intern/stu-internship")
public class StuInternshipController {

    @Value("${pathUrl}")
    private String pathUrl;

    @Autowired
    IUserService userService;

    @Autowired
    private AliyunOssUtil ossUtil;

    @Autowired
    private IStuTeachService stuTeachService;

    @Autowired
    private IUserInternshipService userInternshipService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    IInternshipInfoService internshipInfoService;

    @Autowired
    IStuInternshipService stuInternshipService;

    @PostMapping("/add")
    public R addIntern(@RequestBody InternshipUser intern) {
        User user = new User();
        BeanUtils.copyProperties(intern, user);
        user.setOthername(intern.getInternshipName());
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        //单位
        user.setType(3);
        boolean save = userService.save(user);
        Integer id = user.getId();

        InternshipInfo internshipInfo = new InternshipInfo();
        BeanUtils.copyProperties(intern, internshipInfo);
        internshipInfo.setUid(id);
        boolean save1 = internshipInfoService.save(internshipInfo);

        return R.ok();
    }

    @DeleteMapping("/delete/{iid}")
    public R deleteInternship(@PathVariable Integer iid) {
        System.out.println("iid => " + iid);
        /**
         * 删除用户表
         */
        boolean b = userService.removeById(iid);
        /**
         * 删除实习单位 学生关联表
         */
        QueryWrapper<StuInternship> stuInternshipQueryWrapper = new QueryWrapper<>();
        stuInternshipQueryWrapper.eq("IID", iid);
        List<StuInternship> list = stuInternshipService.list(stuInternshipQueryWrapper);
        boolean remove1 = true;
        if(list.size() >= 1) {
            remove1 = stuInternshipService.remove(stuInternshipQueryWrapper);
        }
        /**
         * 删除实习单位信息表
         */
        QueryWrapper<InternshipInfo> infoQueryWrapper = new QueryWrapper<>();
        infoQueryWrapper.eq("UID", iid);
        boolean remove = internshipInfoService.remove(infoQueryWrapper);
        if (remove && b && remove1) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @PostMapping("/addStuIntern")
    public R addStuIntern(@RequestBody HashMap<String, Integer> VO) {
        StuInternship stuInternship = new StuInternship();
        stuInternship.setIid(VO.get("iid"));
        stuInternship.setSid(VO.get("sid"));

        boolean save = stuInternshipService.save(stuInternship);
        if(save) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 通过iid获取Students列表
     * @param iid
     * @return
     */
    @GetMapping("/stuListByIID/{iid}")
    public R getStuListById(@PathVariable Integer iid)  {
        QueryWrapper<StuInternship> stuInternshipQueryWrapper = new QueryWrapper<>();
        stuInternshipQueryWrapper.eq("IID", iid);
        List<StuInternship> list = stuInternshipService.list(stuInternshipQueryWrapper);
        List<Integer> idList = list.stream().map(StuInternship::getSid).collect(Collectors.toList());
        /**
         * 通过idList得到StudentList
         */
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("TYPE", 1);
        List<User> list1 = new ArrayList<>();
        if(idList.size() >= 1) {
            userQueryWrapper.in("ID", idList);
            list1 = userService.list(userQueryWrapper);
        }
        return R.ok().data("students", list1).data("total", list.size());
    }


    @GetMapping("/getStudentStatus/{sid}")
    public R getStudentStatus(@PathVariable Integer sid) {
        StuInternship one = stuInternshipService.getOne(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getSid, sid));

        if(one != null) {
            return R.ok().data("status", false);
        }else {
            return R.ok().data("status", true);
        }

    }

    /**
     * 获取当前学生的接收函状态
     * @param sid
     * @return
     */
    @GetMapping("/applyGetStatus/{sid}")
    public R applyGetStatus(@PathVariable("sid") Integer sid) {
        StuInternship one = stuInternshipService.getOne(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getSid, sid));
        if(one == null) {
            return R.ok().data("status", 0);
        }
        String unitLetterPath = one.getUnitLetterPath();
        if(unitLetterPath!=null) {
            /**
             * 审核了
             */
            return R.ok().data("status", 2);
        } else {
            if(one.getEndTime()!=null) {
                /**
                 * 审核中
                 */
                return R.ok().data("status", 1);
            }
            return R.ok().data("status", 0);
        }
    }

    /**
     * 学生提交审核
     * @param stuInternship
     * @return
     */
    @PostMapping("/applyCheck")
    public R applyCheck(@RequestBody StuInternship stuInternship) {
        StuInternship one = stuInternshipService.getOne(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getSid, stuInternship.getSid()));
        boolean save = false;
        if(one != null) {
            one.setEndTime(stuInternship.getEndTime());
            one.setStartTime(stuInternship.getStartTime());
            one.setDepartment(stuInternship.getDepartment());
            save = stuInternshipService.updateById(one);
        }else {
            save = stuInternshipService.save(stuInternship);
        }
        return R.ok().data("status", save);
    }

    /**
     * 通过sid获取对应的iid
     * @param sid
     * @return
     */
    @GetMapping("/internshipInfo/{sid}")
    public R getInternshipInfo(@PathVariable Integer sid) {
        StuInternship one = stuInternshipService.getOne(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getSid, sid));
        return R.ok().data("stuInternship", one);
    }

    /**
     * 获取企业对应的学生列表(用于前台查看学生列表)
     * @param iid
     * @return
     */
    @GetMapping("/getStuListByIid/{iid}")
    public R getStuListByIid(@PathVariable Integer iid)  {
        ArrayList<RelevanceUserVo> result = new ArrayList<>();

        QueryWrapper<StuInternship> stuInternshipQueryWrapper = new QueryWrapper<>();
        stuInternshipQueryWrapper.eq("IID", iid);
        List<StuInternship> list = stuInternshipService.list(stuInternshipQueryWrapper);

        list.forEach(item -> {
            RelevanceUserVo relevanceUserVo = new RelevanceUserVo();
            User stu = userService.getById(item.getSid());
            BeanUtils.copyProperties(stu, relevanceUserVo);
            if (item.getStatus() == true) {
                relevanceUserVo.setStatus(2);
            } else {
                relevanceUserVo.setStatus(1);
            }
            relevanceUserVo.setStuName(stu.getOthername());
            relevanceUserVo.setStuId(stu.getId());
            result.add(relevanceUserVo);
        });

//        List<Integer> idList = list.stream().map(StuInternship::getSid).collect(Collectors.toList());
//        /**
//         * 通过idList得到StudentList
//         */
//        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
//        userQueryWrapper.eq("TYPE", 1);
//        List<User> list1 = new ArrayList<>();
//
//        if(idList.size() >= 1) {
//            userQueryWrapper.in("ID", idList);
//            list1 = userService.list(userQueryWrapper);
//        }


        return R.ok().data("students", result).data("total", result.size());
    }


    /**
     * 获取企业对应的学生列表(用于前台查看鉴定表学生列表)
     * @param iid
     * @return
     */
    @GetMapping("/getIdentifyStuListByIid/{iid}")
    public R getIdentifyStuListByIid(@PathVariable Integer iid)  {
        ArrayList<RelevanceUserVo> result = new ArrayList<>();

        QueryWrapper<StuInternship> stuInternshipQueryWrapper = new QueryWrapper<>();
        stuInternshipQueryWrapper.eq("IID", iid);
        List<StuInternship> list = stuInternshipService.list(stuInternshipQueryWrapper);
        list.forEach(item -> {
            RelevanceUserVo relevanceUserVo = new RelevanceUserVo();
            User stu = userService.getById(item.getSid());
            BeanUtils.copyProperties(stu, relevanceUserVo);

            relevanceUserVo.setIid(item.getIid());

            UserInternship one = userInternshipService.getOne(new QueryWrapper<UserInternship>().lambda().eq(UserInternship::getSid, stu.getId()));
            /**
             * 从老师分数判断是否有
             * 设置教师审核状态
             */
            relevanceUserVo.setTeacherStatus(false);
            if (one != null && one.getTeacherGrade() != null && one.getTeacherGrade() > 0) {
                relevanceUserVo.setTeacherStatus(true);
            }
            /**
             * 从企业分数判断是否有
             * 设置企业审核状态
             */
            relevanceUserVo.setInternStatus(false);
            if (one != null && one.getInternshipGrade() != null && one.getInternshipGrade() > 0) {
                relevanceUserVo.setInternStatus(true);
            }

            relevanceUserVo.setStuName(stu.getOthername());
            relevanceUserVo.setStuId(stu.getId());
            /**
             * 显示审核ing 或者审核完毕的学生列表
             */
            if(one !=null && (one.getStatus() == 1 || one.getStatus() == 2)) {
                result.add(relevanceUserVo);
            }
        });

//        List<Integer> idList = list.stream().map(StuInternship::getSid).collect(Collectors.toList());
//        /**
//         * 通过idList得到StudentList
//         */
//        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
//        userQueryWrapper.eq("TYPE", 1);
//        List<User> list1 = new ArrayList<>();
//
//        if(idList.size() >= 1) {
//            userQueryWrapper.in("ID", idList);
//            list1 = userService.list(userQueryWrapper);
//        }


        return R.ok().data("students", result).data("total", result.size());
    }


    /**
     * 通过tid获取对应的students的单位接收函审核情况
     * @param tid
     * @return
     */
    @GetMapping("/stuUnitLetterList/{tid}")
    public R stuUnitLetterList(@PathVariable Integer tid) {
        /**
         * 先获取sidList
         */
        QueryWrapper<StuTeach> stuTeachQueryWrapper = new QueryWrapper<>();
        stuTeachQueryWrapper.eq("TID", tid);
        List<StuTeach> list = stuTeachService.list(stuTeachQueryWrapper);
        List<Integer> sidList = list.stream().map(StuTeach::getSid).collect(Collectors.toList());
        /**
         * 再通过sidList 获取对应的学生列表
         */
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if(!sidList.isEmpty()) {
            userQueryWrapper.in("ID", sidList);
            List<User> stuList = userService.list(userQueryWrapper);
            ArrayList<UnitLetterVo> result = new ArrayList<>();
            stuList.stream().forEach(item -> {
                StuInternship internship = stuInternshipService.getBaseMapper().selectOne(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getSid, item.getId()));
                UnitLetterVo unitLetterVo = new UnitLetterVo();
                unitLetterVo.setAvatar(item.getAvatar());
                unitLetterVo.setId(item.getId());
                unitLetterVo.setEmail(item.getEmail());
                unitLetterVo.setMobliephone(item.getMobilephone());
                unitLetterVo.setSex(item.getSex());
                unitLetterVo.setOtherName(item.getOthername());
                /**
                 * 不为null说明有实习
                 */
                if(internship != null) {
                    /**
                     * 有路径说明已经审核完毕
                     */
                    unitLetterVo.setIid(internship.getIid());
                    if(!StringUtils.isEmpty(internship.getUnitLetterPath())) {
                        unitLetterVo.setStatus(3);
                    }else {
                        unitLetterVo.setStatus(2);
                    }
                }else {
                    unitLetterVo.setStatus(1);
                }
                result.add(unitLetterVo);
            });
            return R.ok().data("students", result);
        }else {
            return R.ok().data("students", null);
        }
    }

    /**
     * 通过iid获取对应的students的单位接收函审核情况
     * @param iid
     * @return
     */
    @GetMapping("/stuUnitLetterCheckList/{iid}")
    public R stuUnitLetterCheckList(@PathVariable Integer iid) {
        /**
         * 先获取sidList
         */
        QueryWrapper<StuInternship> stuInternshipQueryWrapper = new QueryWrapper<>();
        stuInternshipQueryWrapper.eq("IID", iid);
        List<StuInternship> list = stuInternshipService.list(stuInternshipQueryWrapper);
        List<Integer> sidList = list.stream().map(StuInternship::getSid).collect(Collectors.toList());
        /**
         * 再通过sidList 获取对应的学生列表
         */
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if(!sidList.isEmpty()) {
            userQueryWrapper.in("ID", sidList);
            List<User> stuList = userService.list(userQueryWrapper);
            ArrayList<UnitLetterVo> result = new ArrayList<>();
            stuList.stream().forEach(item -> {
                StuInternship internship = stuInternshipService.getBaseMapper().selectOne(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getSid, item.getId()));
                UnitLetterVo unitLetterVo = new UnitLetterVo();
                unitLetterVo.setId(item.getId());
                unitLetterVo.setIid(iid);
                unitLetterVo.setAvatar(item.getAvatar());
                unitLetterVo.setEmail(item.getEmail());
                unitLetterVo.setMobliephone(item.getMobilephone());
                unitLetterVo.setSex(item.getSex());
                unitLetterVo.setOtherName(item.getOthername());
                /**
                 * 不为null说明有实习
                 */
                if(internship != null) {
                    /**
                     * 有路径说明已经审核完毕
                     */
                    if(!StringUtils.isEmpty(internship.getUnitLetterPath())) {
                        unitLetterVo.setStatus(3);
                    }else {
                        unitLetterVo.setStatus(2);
                    }
                }else {
                    unitLetterVo.setStatus(1);
                }
                result.add(unitLetterVo);
            });
            return R.ok().data("students", result);
        }else {
            return R.ok().data("students", null);
        }
    }


    /**
     * 移除学生企业关系
     * @param sid
     * @return
     */
    @DeleteMapping("/removeStuIntern/{sid}")
    public R removeStuIntern(@PathVariable Integer sid) {
        UserInternship one = userInternshipService.getOne(new QueryWrapper<UserInternship>().lambda().eq(UserInternship::getSid, sid));
        boolean remove1 = userInternshipService.removeById(one);
        QueryWrapper<StuInternship> stuInternshipQueryWrapper = new QueryWrapper<>();
        stuInternshipQueryWrapper.eq("SID", sid);
        boolean remove = stuInternshipService.remove(stuInternshipQueryWrapper);
        if(remove) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    /**
     * 获取单位接收函状态
     * @param sid
     * @param iid
     * @return
     */
    @GetMapping("/getUnitLetterStatus")
    public R getUnitLetterStatus(@RequestParam(required = true) Integer sid,
                                 @RequestParam(required = false) Integer iid) {
        if(iid.equals(null)) {
            return R.ok().message("请先加入企业").data("type", 0);
        }
        StuInternship stuInternship = stuInternshipService.getBaseMapper().selectOne(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getSid, sid).eq(StuInternship::getIid, iid));
        String unitLetterPath = stuInternship.getUnitLetterPath();
        if(StringUtils.isEmpty(unitLetterPath)) {
            return R.ok().message("是否生成就业推荐表").data("type", 1);
        }
        String ossUrl = pathUrl.concat(unitLetterPath);
        String previewUrl = "/js/web/viewer.html?file=/EasypoiSingleExcelViewTest/preview/" + sid + "/" + iid;

        return R.ok().message("就业推荐表已生成完毕").data("type", 2).data("ossUrl", ossUrl).data("previewUrl", previewUrl);
    }


    /**
     * 生成单位接收函
     * 生成 word <b>并且</b> 转换pdf
     * @param stuInternship
     * @param modelMap
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/makeUnitLetter")
    public R makeUnitLetter(@RequestBody StuInternship stuInternship,
                           ModelMap modelMap,
                           HttpServletRequest request,
                           HttpServletResponse response) {
        Integer iid = stuInternship.getIid();
        Integer sid = stuInternship.getSid();
        StuInternship stuInternship1 = stuInternshipService.getBaseMapper().selectOne(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getIid, iid).eq(StuInternship::getSid, sid));
        InternshipInfo intern = internshipInfoService.getOne(new QueryWrapper<InternshipInfo>().lambda().eq(InternshipInfo::getUid, iid));

        User stuIntern = userService.getById(iid);
        User student = userService.getById(sid);
        UnitLetter unitLetter = new UnitLetter();
        unitLetter.setId(stuInternship1.getId());
        unitLetter.setDepartment(student.getDepartment());
        unitLetter.setMajor(student.getGrade());
        unitLetter.setStudentName(student.getOthername());
        unitLetter.setStartTime(stuInternship1.getStartTime());
        unitLetter.setEndTime(stuInternship1.getEndTime());
        unitLetter.setWorkDepartment(stuInternship1.getDepartment());
        unitLetter.setUnitName(stuIntern.getOthername());
        unitLetter.setUnitLocation(intern.getLocationInfo());
        unitLetter.setUnitContactPerson(intern.getContactPerson());
        unitLetter.setUnitPhone(stuIntern.getMobilephone());


        String url = "exceltohtml/UnitLetter.docx";
        TemplateExportParams params = new TemplateExportParams(url);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("entity", unitLetter);


        modelMap.put(TemplateWordConstants.FILE_NAME, "UnitLetter");
        modelMap.put(TemplateWordConstants.PARAMS, params);
        modelMap.put(TemplateWordConstants.MAP_DATA, map);
        modelMap.put(TemplateWordConstants.URL, url);
        boolean b = false;
        try {
            b = renderMergedOutputModel(modelMap, request, response, stuInternship1.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message(e.getMessage());
        }
        if(!b) {
            return R.error().message("无更新");
        }
        return R.ok();
    }


    /**
     * 生成实习鉴定表
     * @param userInternship
     * @param modelMap
     * @param request
     * @param response
     */
    @SneakyThrows
    @PostMapping("/makeUnitForm")
    public void download01(@RequestBody UserInternship userInternship,
                           ModelMap modelMap, HttpServletRequest request,
                           HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        String url = "exceltohtml/UnitForm.docx";
        TemplateExportParams params = new TemplateExportParams(url);
        List<TestPoiWord> list = new ArrayList<TestPoiWord>();
        /**
         * 找到对应的userInternship对象
         */
        Integer sid = userInternship.getSid();
        userInternship = userInternshipService.getOne(new QueryWrapper<UserInternship>().lambda().eq(UserInternship::getSid, sid).eq(UserInternship::getDeleted, 0));


        StuInternship stuInternship = stuInternshipService.getOne(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getSid, sid));

        User stu = userService.getById(sid);
        User internship = userService.getById(stuInternship.getIid());

        TestPoiWord student = new TestPoiWord();
        student.setDepartment(stu.getDepartment());
        student.setGrade(stu.getGrade());
        /**
         * 时间格式化
         */
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        student.setInternshipDate(userInternship.getCreateTime().format(dtf));
        student.setInternshipUnit(internship.getOthername());
        student.setMajor(stu.getMajor());
        student.setStudentName(stu.getOthername());
        student.setStudentNo(stu.getUsername().toString());
//        list.add(student);
        map.put("student", student);

        String endTime = userInternship.getInternshipEndTime().format(dtf);
        String startTime = userInternship.getInternshipStartTime().format(dtf);
        userInternship.setEndTime(endTime);
        userInternship.setStartTime(startTime);

        StuTeach stuTeach = stuTeachService.getOne(new QueryWrapper<StuTeach>().lambda().eq(StuTeach::getSid, sid));
        User teacher = userService.getById(stuTeach.getTid());
        userInternship.setTeacher(teacher.getOthername());
        userInternship.setInternship(internship.getOthername());

        map.put("userInternship", userInternship);

        String signature = internship.getSignature();
        if(!StringUtils.isEmpty(signature)) {
            WordImageEntity companyImg = new WordImageEntity();
            companyImg.setHeight(100);
            companyImg.setWidth(100);
            companyImg.setType(WordImageEntity.Data);
            companyImg.setData(TransUtils.image2byte(signature));
            map.put("companyImg", companyImg);
        }

        String signature1 = teacher.getSignature();
        if (!StringUtils.isEmpty(signature1)) {
            WordImageEntity teacherImg = new WordImageEntity();
            teacherImg.setHeight(50);
            teacherImg.setWidth(100);
            teacherImg.setType(WordImageEntity.Data);
            teacherImg.setData(TransUtils.image2byte(signature1));
            map.put("teacherImg", teacherImg);
        }


        modelMap.put(TemplateWordConstants.FILE_NAME, "UnitForm");
        modelMap.put(TemplateWordConstants.PARAMS, params);
        modelMap.put(TemplateWordConstants.MAP_DATA, map);
        modelMap.put(TemplateWordConstants.URL, url);
//        PoiBaseView.render(modelMap, request, response,
//                TemplateWordConstants.EASYPOI_TEMPLATE_WORD_VIEW);
        try {
            makeUnitForm(modelMap, request, response, stuInternship.getId(), userInternship);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 接收函
     * @param model
     * @param request
     * @param response
     * @param id
     * @return
     * @throws Exception
     */
    protected boolean renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response, Integer id) throws Exception {
        /**
         * 通过id获取stuIntern 关联对象
         */
        StuInternship internship = stuInternshipService.getById(id);
        /**
         * 本地pdf
         */
        String localPDFPath = LocalVariables.localPdfPath;
        String codedFileName = "swapTime.docx";

        if (model.containsKey("fileName")) {
            codedFileName = (String)model.get("fileName") + ".docx";
        }

        codedFileName = URLEncoder.encode(codedFileName, "UTF8");
        response.setHeader("content-disposition", "attachment;filename=" + codedFileName);
        XWPFDocument document = WordExportUtil.exportWord07((String)model.get("url"), (Map)model.get("map"));

//        ServletOutputStream out = response.getOutputStream();
//        document.write(out);

        File newFile = new File(codedFileName);
        FileOutputStream os = new FileOutputStream(newFile);
        document.write(os);
        os.close();
        String upload = ossUtil.upload(newFile);
        /**
         * 将newFile 复制一份到本地， 本地做word转pdf
         */
        InputStream inputStream = new FileInputStream(newFile);

        Boolean aBoolean = TransUtils.wordToPdf(inputStream, localPDFPath);

        if(aBoolean) {
            /**
             *  然后将pdf也上传到oss
             */
            File file = new File(localPDFPath);

            String pdfPath = ossUtil.upload(file);
            System.out.println("pdfPath => " + pdfPath);

            /**
             * todo 持久化到数据库
             */
            internship.setUnitLetterPdfPath(pdfPath);
        }

        internship.setUnitLetterPath(upload);
        int i = stuInternshipService.getBaseMapper().updateById(internship);
        if(i == 0) {
            return false;
        }

        return true;
    }

    /**
     * 鉴定表
     * @param model
     * @param request
     * @param response
     * @param id
     * @return
     * @throws Exception
     */
    protected boolean makeUnitForm(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response, Integer id, UserInternship userInternship) throws Exception {
        /**
         * 通过id获取stuIntern 关联对象
         */
        StuInternship internship = stuInternshipService.getById(id);
        /**
         * 本地pdf
         */
        String localPDFPath = LocalVariables.localPdfPath;
        String codedFileName = "swapTime.docx";

        if (model.containsKey("fileName")) {
            codedFileName = (String)model.get("fileName") + ".docx";
        }

        codedFileName = URLEncoder.encode(codedFileName, "UTF8");
        response.setHeader("content-disposition", "attachment;filename=" + codedFileName);
        XWPFDocument document = WordExportUtil.exportWord07((String)model.get("url"), (Map)model.get("map"));

//        ServletOutputStream out = response.getOutputStream();
//        document.write(out);

        File newFile = new File(codedFileName);
        FileOutputStream os = new FileOutputStream(newFile);
        document.write(os);
        os.close();
        String upload = ossUtil.upload(newFile);
        /**
         * 将newFile 复制一份到本地， 本地做word转pdf
         */
        InputStream inputStream = new FileInputStream(newFile);

        Boolean aBoolean = TransUtils.wordToPdf(inputStream, localPDFPath);

        if(aBoolean) {
            /**
             *  然后将pdf也上传到oss
             */
            File file = new File(localPDFPath);

            String pdfPath = ossUtil.upload(file);
            System.out.println("pdfPath => " + pdfPath);

            /**
             * todo 持久化到数据库
             */
            internship.setInternFormPdfPath(pdfPath);
        }

        internship.setInternFormPath(upload);
        int i = stuInternshipService.getBaseMapper().updateById(internship);
        /**
         * 审核完毕
         */
        userInternship.setStatus(2);
        userInternshipService.updateById(userInternship);

        if(i == 0) {
            return false;
        }

        return true;
    }


}
